<?php
/**
 * Created by PhpStorm.
 * User: WYJ
 * Date: 2018/5/8
 * Time: 15:39
 */

namespace zhtfrontend\controllers;

use common\components\helpers\Fun;
use common\models\datas\Cate;
use common\models\datas\Student;
use doumiaoduo\buildform\BuildForm;
use yii\data\Pagination;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Response;
use yii\widgets\ActiveForm;
use zhtfrontend\components\bases\BaseController;
use common\components\actions\DeleteAction;
use zhtfrontend\components\services\customermanage\Index;
use zhtfrontend\models\datas\Admin;
use zhtfrontend\models\datas\CustomerRelationship;
use zhtfrontend\models\datas\CustomerReturnVisit;

class CustomerrelationshipController extends BaseController
{

    //列表
    public function actionIndex()
    {
        echo 'Xdebug';
        $data_array=[];
        $param['searchData'] = \Yii::$app->request->get();
        $category = (new Query())->select('id,name')->from('{{%cate}}')->where(['parent_id' => 0])->all();
        $site_id = Fun::getSiteId();
        $model = [];
        $data = CustomerRelationship::find()->where(['site_id' => $site_id]);
        if (!empty($param['searchData'])) {
            $search_data = array_filter($param['searchData']);
            //手机号搜索
            if (!empty($search_data['tel'])) {
                $data->andWhere(['mobile' => $search_data['tel']]);
            }
            //姓名搜索
            if (!empty($search_data['name'])) {
                $data->andWhere(['name' => $search_data['name']]);
            }
            //意向分类搜索
            if (!empty($search_data['category_id'])) {
                $data->andWhere(['category_id' => $search_data['category_id']]);
            }
            //获客渠道搜索
            if (!empty($search_data['source'])) {
                $data->andWhere(['source' => $search_data['source']]);
            }
            //客户类型搜索
            if (!empty($search_data['status'])) {
                $data->andWhere(['status' => $search_data['status']]);
            }
        }
        if (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role == 'customer_manager') {
            $data->andWhere(['admin_id' => \Yii::$app->user->identity->id]);;
        }
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 20;
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        //超级管理员和营销主管
        if (isset(\Yii::$app->user->identity) && in_array(\Yii::$app->user->identity->role, ['admin', 'administrator','marketing_director','sales_director'])) {
            $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        } elseif (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role=='marketing_commissioner'){//营销专员
            $admin_child_ids=(new Query())->select('admin_child_ids')->from('{{%customer_relationship}}')
                ->where(['not',['admin_child_ids'=>null]])->column(Fun::getSiteDb());
            $admin_child_ids_array=[];
            foreach ($admin_child_ids as $key=>$val){
                $admin_array = explode(',', $val);
                if(in_array(\Yii::$app->user->id,$admin_array)){
                    $admin_child_ids_array[]=$val;
                }
            }
            $model=$data->andWhere(['or', 'admin_id'=>\Yii::$app->user->id, ['in', 'admin_child_ids', $admin_child_ids_array]]);

        }elseif (isset(\Yii::$app->user->identity) && \Yii::$app->user->identity->role=='sales_specialist'){
            $model=$data->andWhere(['salesman_id'=>\Yii::$app->user->id]);
        }else {
            if (!empty($param['searchData']['tel']) || !empty($param['searchData']['name'])) $model = $data->all();
        }

        //匹配手机号，如果customer表中有数据则以customer表为准
        foreach ($model as $k => $v) {
            $customer = (new Query())->select('*')->from('{{%customer}}')->where(['mobile' => $v->mobile])->one();
            if (isset($customer) && !empty($customer)) {
                $v->name = $customer['name'];
                $v->sex = ($customer['sex'] == 'Female') ? '1' : '0';
            }
            $data_array[] = $v;
        }
        $array = Fun::asArray($data_array, ['operate']);
        return $this->render('index', [
            'data' => $array,
            'pages' => $pages,
            'category' => $category
        ]);

    }

    //添加
    public function actionCreate()
    {
        $this->layout = false;
        $model = new CustomerRelationship();
        // $model->scenario = 'create';
        $model->site_id = Fun::getSiteId();
        $form = new BuildForm('@app/components/forms/customerrelationshipForm.php');
        $form->loadModel(['customerrelationship' => $model]);
        $site_id = Fun::getSiteId();

        //分类类别
        $category = Cate::find()->where(['parent_id' => 0])->asArray()->all();
        $form->setItems('customerrelationship', 'category_id', ArrayHelper::map($category, 'id', 'name'));

        $marketing_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['marketing_director', 'marketing_commissioner']])->all();
        //负责人
        $form->setItems('customerrelationship', 'admin_id', ArrayHelper::map($marketing_admin, 'id', 'name'));
        //副负责人
        //$form->setData('customerrelationship', 'admin_child_ids', 'data', $marketing_admin);
        //$form->setItems('customerrelationship', 'admin_child_ids', ArrayHelper::map($marketing_admin, 'id', 'name'));

        //客户来源
        $source_arr = [['id' => '1', 'name' => '电话'], ['id' => '2', 'name' => '地推'], ['id' => '3', 'name' => '其他']];
        $form->setItems('customerrelationship', 'source', ArrayHelper::map($source_arr, 'id', 'name'));

        //客户类别
        $status_arr = [['id' => '0', 'name' => '潜在客户'], ['id' => '1', 'name' => '意向客户'], ['id' => '2', 'name' => '正式VIP']];
        $form->setItems('customerrelationship', 'status', ArrayHelper::map($status_arr, 'id', 'name'));

        //客户成熟度
        $maturity_arr = [
            ['val' => 'A+', 'title' => '明确成交意向'],
            ['val' => 'A-', 'title' => '有初步成交意向'],
            ['val' => 'B+', 'title' => '初步联系，有意向'],
            ['val' => 'B-', 'title' => '初步联系，意向不确定'],
            ['val' => 'C', 'title' => '无效客户'],
            ['val' => 'D', 'title' => '明显拒绝'],
        ];
        $form->setItems('customerrelationship', 'maturity', ArrayHelper::map($maturity_arr, 'val', 'title'));

        //跟进负责人
        /* $salesman_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['sales_director', 'sales_specialist']])->all();
         $form->setItems('customerrelationship', 'salesman_id', ArrayHelper::map($salesman_admin, 'id', 'name'));*/

        //获客渠道
        $channel = [['id' => 0, 'title' => '校区'], ['id' => 1, 'title' => '片区'], ['id' => 2, 'title' => '其他']];
        $form->setItems('customerrelationship', 'channel', ArrayHelper::map($channel, 'id', 'title'));

        //ajax 验证操作,
        if (\Yii::$app->request->post('ajax') == 'customerrelationship-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $post = \Yii::$app->request->post()['CustomerRelationship'];
            $model = $form->getModel('customerrelationship');
            $model->site_id = $site_id;
            $model->admin_child_ids = implode(',', $post['admin_child_ids']);
            if ($model->save(false)) {
                return $this->redirectMessage('添加成功', Fun::url(['customerrelationship/index']));
            }

        }
        return $this->render('create', ['form' => $form->render()]);

    }

    //修改
    public function actionUpdate()
    {
        $this->layout = false;
        $id = \Yii::$app->request->get('id');
        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = CustomerRelationship::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $form = new BuildForm('@app/components/forms/customerrelationshipForm.php');
        $form->loadModel(['customerrelationship' => $model]);

        //分类类别
        $category = Cate::find()->where(['parent_id' => 0])->asArray()->all();
        $form->setItems('customerrelationship', 'category_id', ArrayHelper::map($category, 'id', 'name'));

        //$marketing_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['marketing_director', 'marketing_commissioner']])->all();
        //负责人
        // $form->setItems('customerrelationship', 'admin_id', ArrayHelper::map($marketing_admin, 'id', 'name'));

        //副负责人

        //客户来源
        $source_arr = [['id' => '1', 'name' => '电话'], ['id' => '2', 'name' => '地推'], ['id' => '3', 'name' => '其他']];
        $form->setItems('customerrelationship', 'source', ArrayHelper::map($source_arr, 'id', 'name'));

        //客户类别
        $status_arr = [
            ['id' => '0', 'name' => '潜在客户'],
            ['id' => '1', 'name' => '意向客户'],
            ['id' => '2', 'name' => '正式VIP']
        ];
        $form->setItems('customerrelationship', 'status', ArrayHelper::map($status_arr, 'id', 'name'));

        //客户成熟度
        $maturity_arr = [
            ['val' => 'A+', 'title' => '明确成交意向'],
            ['val' => 'A-', 'title' => '有初步成交意向'],
            ['val' => 'B+', 'title' => '初步联系，有意向'],
            ['val' => 'B-', 'title' => '初步联系，意向不确定'],
            ['val' => 'C', 'title' => '无效客户'],
            ['val' => 'D', 'title' => '明显拒绝'],
        ];
        $form->setItems('customerrelationship', 'maturity', ArrayHelper::map($maturity_arr, 'val', 'title'));

        //跟进负责人
        /* $salesman_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['sales_director', 'sales_specialist']])->all();
         $form->setItems('customerrelationship', 'salesman_id', ArrayHelper::map($salesman_admin, 'id', 'name'));*/

        //获客渠道
        $channel = [['id' => 0, 'title' => '校区'], ['id' => 1, 'title' => '片区'], ['id' => 2, 'title' => '其他']];
        $form->setItems('customerrelationship', 'channel', ArrayHelper::map($channel, 'id', 'title'));

        //ajax 验证操作,
        if (\Yii::$app->request->post('ajax') == 'customerrelationship-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($form->loadData(\Yii::$app->request->post()) && $form->validate()) {
            $post = \Yii::$app->request->post()['CustomerRelationship'];
            $model->admin_child_ids = implode(',', $post['admin_child_ids']);
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '信息修改成功'), Fun::url(['customerrelationship/index']));
            }
        }
        return $this->render('create', ['form' => $form->render()]);

    }

    //销售分派
    public function actionAssignment()
    {
        $this->layout = false;
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = CustomerRelationship::findOne($id);
        $salesman_id=$model->salesman_id;
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $form = new BuildForm('@app/components/forms/assignmentForm.php');
        $form->loadModel(['assignment' => $model]);

        //跟进负责人
        $salesman_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['sales_director', 'sales_specialist']])->all();
        $form->setItems('assignment', 'salesman_id', ArrayHelper::map($salesman_admin, 'id', 'name'));

        //ajax 验证操作,
        if (\Yii::$app->request->post('ajax') == 'assignment-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($form->loadData(\Yii::$app->request->post())) {
            $post=\Yii::$app->request->post()['CustomerRelationship'];
            if($post['is_assign']==1){
                $return_visit=CustomerReturnVisit::find()->where(['mobile'=>$model->mobile, 'admin_id' => $salesman_id])->all();
                if(isset($return_visit)){
                    CustomerReturnVisit::updateAll(['follow_status' => 1], ['mobile' => $model->mobile, 'admin_id' => $salesman_id]);
                }
                if ($model->save(false)) {
                    return $this->redirectMessage(\Yii::t('zhtfrontend', '分派成功'), Fun::url(['customerrelationship/index']));
                }
            }else{
                return $this->redirectMessage(\Yii::t('zhtfrontend', '分派失败'), Fun::url(['customerrelationship/index']));
            }

        }

        return $this->render('assignment', ['form' => $form->render()]);
    }

    public function actionRecoveryassign()
    {
        $this->layout = false;
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = CustomerRelationship::findOne($id);
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $form = new BuildForm('@app/components/forms/recoveryassignForm.php');
        $form->loadModel(['recoveryassign' => $model]);

        $marketing_admin = Admin::find()->where(['status' => 1])->andWhere(['in', 'role', ['marketing_director', 'marketing_commissioner']])->all();
        //负责人
         $form->setItems('recoveryassign', 'admin_id', ArrayHelper::map($marketing_admin, 'id', 'name'));

        //ajax 验证操作,
        if (\Yii::$app->request->post('ajax') == 'recoveryassign-form' && $form->loadData(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }

        if ($form->loadData(\Yii::$app->request->post())) {
            if ($model->save(false)) {
                return $this->redirectMessage(\Yii::t('zhtfrontend', '分派成功'), Fun::url(['customerrelationship/index']));
            }
        }
        return $this->render('recoveryassign', ['form' => $form->render()]);
    }

    //查看详情
    public function actionDetail()
    {
        $id = \Yii::$app->request->get('id');

        if (\Yii::$app->request->get('id') == null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }
        $model = CustomerRelationship::find()->where(['id' => $id])->asArray()->one();
        if ($model === null) {
            throw new BadRequestHttpException(\Yii::t('zhtfrontend', '信息不存在'), 404);
        }

        $customer = (new Query())->select('*')->from('{{%customer}}')
            ->where(['mobile' => $model['mobile'], 'site_id' => Fun::getSiteId()])->one();

        //意向分类
        $category = (new Query())->select('*')->from('{{%cate}}')->where(['id' => $model['category_id']])->one();
        $model['category_id'] = (isset($category)) ? $category['name'] : '暂无';

        //性别
        switch ($model['sex']) {
            case 0:
                $model['sex'] = '男';
                break;
            case 1:
                $model['sex'] = '女';
                break;
        }

        //客户状态
        switch ($model['status']) {
            case 0:
                $model['status'] = '潜在客户';
                break;
            case 1:
                $model['status'] = '意向客户';
                break;
            case 2:
                $model['status'] = '正式VIP';
                break;
        }

        //客户成熟度
        switch ($model['maturity']) {
            case 'A+':
                $model['maturity'] = '明确成交意向';
                break;
            case 'A-':
                $model['maturity'] = '有初步成交意向';
                break;
            case 'B+':
                $model['maturity'] = '初步联系，有意向';
                break;
            case 'B-':
                $model['maturity'] = '初步联系，意向不确定';
                break;
            case 'C':
                $model['maturity'] = '无效客户';
                break;
            case 'D':
                $model['maturity'] = '明显拒绝';
                break;
        }

        //客户来源
        switch ($model['source']) {
            case 0:
                $model['status'] = '电话';
                break;
            case 1:
                $model['status'] = '地推';
                break;
            case 2:
                $model['status'] = '其他';
                break;
        }

        //获客渠道

        //负责人
        $responsibility_man = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $model['admin_id']])->one(Fun::getSiteDb());
        $model['admin_id'] = $responsibility_man['name'];

        //副负责人
        $vice_responsibility_man = (new Query())->select('name')->from('{{%admin}}')
            ->where(['in', 'id', explode(',', $model['admin_child_ids'])])->column(Fun::getSiteDb());
        $model['admin_child_ids'] = implode('/', $vice_responsibility_man);

        //跟进负责人
        $salesman = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $model['salesman_id']])->one(Fun::getSiteDb());
        $model['salesman_id'] = $salesman['name'];

        //是否注册
        $model['is_customer'] = (isset($customer)) ? '已注册' : '未注册';

        //是否绑定学员
        $model['is_student'] = '没有绑定学员';
        if (isset($customer)) {
            $student = Student::find()->where(['customer_id' => $customer['id']])->asArray()->all();
            if (isset($student)) {
                $model['is_student'] = '绑定' . count($student) . '位学员';
            }
        }

        //是否消费
        $model['is_buy'] = '该客户未消费过';
        if (isset($customer)) {
            $orders = (new Query())->select('*')->from('{{%orders}} o')
                ->leftJoin('{{%orders_items_relation}} oir', 'o.id=oir.orders_id')
                ->where(['oir.customer_id' => $customer['id']])->all(Fun::getSiteDb());
            if (isset($orders)) {
                $model['is_buy'] = '该客户购买过产品';
            }
        }
        $back_url = Fun::url(['customerrelationship/index']);
        return $this->render('detail', ['data' => $model, 'back_url' => $back_url]);

    }

    //删除
    public function actions()
    {
        return [
            'delete' => [
                'class' => DeleteAction::className(),
                'modelClass' => CustomerRelationship::className(),
                'message' => ['success' => '删除成功！'],
                'redirectTo' => 'customerrelationship/index',
            ],
        ];
    }

}